package com.clusterswisdom.horn.api.ioc.api;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.DocumentException;

import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornPropertyParser;

public class HornConfig {
	
	public static final String SCOPE_RUNTIME = "runtime";

	public static HornConfig config = new HornConfig();
	
	private String scope;
	
	private boolean initDebug;
	
	private Map<String, ChannelConfig> channelMap = new HashMap<String, ChannelConfig>();
	
	private Map<String, String> properties = new HashMap<String, String>();
	
	public static HornConfig getConfig() {
		return config;
	}
	
	public boolean isRuntime() {
		return SCOPE_RUNTIME.equals(scope);
	}
	
	public void addServiceConfig(String channel, InputStream is) throws DocumentException {
		ChannelConfig channelConfig = channelMap.get(channel);
		if (channelConfig == null) {
			channelConfig = new ChannelConfig(channel);
			channelMap.put(channel, channelConfig);
		}
		
		channelConfig.addServiceConfig(is);
	}
	
	public ApiConfig getApiConfig(String channel, String service, String api) {
		ChannelConfig channelConfig = channelMap.get(channel);
		return channelConfig.getApiConfig(service, api);
	}
	
	public void addProperty(String key, String value) {
		properties.put(key, value);
	}
	
	public String getProperty(String key) {
		return properties.get(key);
	}
	
	public void addChannelAciton(String channel, HornAction defaultAction) {
		ChannelConfig channelConfig = channelMap.get(channel);
		if (channelConfig == null) {
			channelConfig = new ChannelConfig(channel);
			channelMap.put(channel, channelConfig);
		}
		
		channelConfig.setDefaultAction(defaultAction);
	}
	
	public HornAction getDefualtAction(String channel) {
		ChannelConfig channelConfig = channelMap.get(channel);
		if (channelConfig == null) {
			return null;
		}
		
		return channelConfig.getDefaultAction();
	}
	
	public void setChannelParamParser(String channel, HornPropertyParser propertyParser) {
		ChannelConfig channelConfig = channelMap.get(channel);
		if (channelConfig == null) {
			channelConfig = new ChannelConfig(channel);
			channelMap.put(channel, channelConfig);
		}
		
		channelConfig.setPropertyParser(propertyParser);
	}
	
	public HornPropertyParser getPropertyParser(String channel) {
		ChannelConfig channelConfig = channelMap.get(channel);
		if (channelMap == null) {
			return null;
		}
		
		return channelConfig.getPropertyParser();
	}

	public String getScope() {
		return scope;
	}

	public void setScope(String scope) {
		this.scope = scope;
	}

	public boolean isInitDebug() {
		return initDebug;
	}

	public void setInitDebug(boolean initDebug) {
		this.initDebug = initDebug;
	}
}
